package top.byteio.common.s3.config;

import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.presigner.S3Presigner;
import top.byteio.common.s3.S3Template;
import top.byteio.common.s3.strategy.DefaultStorageStrategy;

import java.net.URI;

@Slf4j
@AllArgsConstructor
@EnableConfigurationProperties(S3Properties.class)
public class S3AutoConfig {
    @Resource
    private S3Properties s3Properties;

    @Bean
    @ConditionalOnMissingBean
    public S3Client s3Client() {
        AwsBasicCredentials cred = AwsBasicCredentials
                .create(s3Properties.getAccessKey(), s3Properties.getSecretKey());
        return S3Client
                .builder()
                .endpointOverride(URI.create(s3Properties.getEndpoint()))
                .region(Region.of(s3Properties.getRegion()))
                .forcePathStyle(s3Properties.getPathStyleAccess())
                .credentialsProvider(StaticCredentialsProvider.create(cred))
                .build();
    }

    @Bean
    @ConditionalOnMissingBean
    public S3Presigner s3Presigner(){
        return S3Presigner.builder()
                .credentialsProvider(
                        () -> new AwsCredentials() {
                            @Override
                            public String accessKeyId() {
                                return s3Properties.getAccessKey();
                            }

                            @Override
                            public String secretAccessKey() {
                                return s3Properties.getSecretKey();
                            }
                        }
                )
                .endpointOverride(URI.create(s3Properties.getEndpoint()))
                .region(Region.of(s3Properties.getRegion()))
                .s3Client(s3Client())
                .endpointOverride(URI.create(s3Properties.getEndpoint()))
                .build();
    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(name = "jole.common.s3.properties.enable", havingValue = "true", matchIfMissing = true)
    public S3Template s3Template(S3Client s3Client,S3Presigner s3Presigner) {
        log.info("jole-storage 成功启用 StorageTemplate");
        return new S3Template(s3Properties,s3Client,s3Presigner,new DefaultStorageStrategy());
    }
}
